import json
import pickle
import socket
import re

from Exception import pwdError
from _config import upd_cli


class Sister:

    def __init__(self, *, maxSize=1024, Config):
        self.maxSize = maxSize
        self.Config = Config
        self.console = self.Config.GetConsoleLog()
        self.port = self.Config.GetPort()

        self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

        self.ip = socket.gethostbyname(socket.gethostname())
        self.soc.bind((self.ip, self.port))
        self.das = ...
        self.Hand = ...

    def wait_task(self):
        """

        :return:
        """
        count = 3

        self.console.using_method(
            f"【Sister_等待中】Sister 服务器 {self.ip}:{self.port} 开始等待 Oneesama的加入{'.'}"
        )
        upd_tmp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        upd_tmp.bind(("",self.port - 1))

        pwd, client_addr_info  = upd_tmp.recvfrom(200)
        if pwd != b'Hello,I am Your Master':
            self.console.using_method("有Oneesama加入但是密码不正确")

        self.console.using_method(
            f"【Sister_接受到了服务器】 Sister 找到了自己的Oneesama ! ip:{client_addr_info[0]} port:{client_addr_info[1]}")

        upd_tmp.close()

        self.join_oneesama(client_addr_info)

    def join_oneesama(self, client_addr_info):
        """
        加入Oneesama服务器
        :return:
        """

        self.soc.connect((client_addr_info[0],10033))

        # region 等待
        self.console.using_method(
            f"【Sister】 开始等待{client_addr_info[0]}:10033的数据"
        )
        byte_dats = self.soc.recv(1024000000)  # 最大接受 1024000Byte 的数据
        self.console.using_method(
            f"【Sister】 等待到了字节大小为{byte_dats.__sizeof__()}大小的数据"
        )
        self.console.using_method(
            f"【Sister】 开始等待{client_addr_info[0]}:10033的任务"
        )
        byte_task = self.soc.recv(1024)
        self.console.using_method(
            f"【Sister】 等待到了{client_addr_info[0]}:10033的任务"
        )
        self.console.using_method(
            f"【Sister】 开始等待{client_addr_info[0]}:10033的任务实参"
        )
        byte_arg = self.soc.recv(1024)
        self.console.using_method(
            f"【Sister】 等待到了{client_addr_info[0]}:10033的任务实参"
        )
        # endregion 等待

        print()
        data = pickle.loads(byte_dats)
        task = byte_task.decode()
        name = re.findall("def (\w*)\(", task)
        name = name[0]
        code = ...
        print(f"{name}{arg}")
        exec (f"{name}{arg}")


    def __del__(self):
        self.console.using_method(
            f"【Sister】 关闭处理服务器"
        )
        self.soc.close()



def recv_dasAndTask(self):
    ...
